package yb.ecp.fast.user.service.base;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.springframework.transaction.annotation.Transactional;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.user.dao.mapper.base.BaseMapper;
import yb.ecp.fast.user.infra.ErrorCode;

import java.util.List;

/**
 * Created by root on 2017-11-29.
 * V:模型类类型，D:实体类类型
 */
public class BaseService<V, D> extends BaseTransVODOService<V, D> {

    BaseMapper baseMapper;

    protected BaseService(Class<V> vClass, Class<D> dClass) {
        super(vClass,dClass);
    }

    protected void addMapper(BaseMapper baseMapper){
        this.baseMapper=baseMapper;
    }

    protected ErrorCode checkParam(V v) {
        if (v == null) {
            return ErrorCode.IllegalArument;
        }
        return ErrorCode.Success;
    }

    public PageCommonVO list(SearchCommonVO<V> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<D> doList = baseMapper.list(condition.getFilters());
        List<V> voList = getVOList(doList);
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    @Transactional
    public ErrorCode insert(V v) {
        ErrorCode ret = checkParam(v);
        if (ret != ErrorCode.Success) {
            return ret;
        }
        D d = getDO(v);

        int effectRow= baseMapper.insert(d);
        return effectRow > 0 ? ErrorCode.Success : ErrorCode.FailedToInsertRecord;
    }

    @Transactional
    public ErrorCode update(V v) {
        ErrorCode ret = checkParam(v);
        if (ret != ErrorCode.Success) {
            return ret;
        }
        D d = getDO(v);

        int effectRow= baseMapper.update(d);
        return effectRow > 0 ? ErrorCode.Success : ErrorCode.FailedToUpdateRecord;
    }
    
    public V item(String no) {
        try {
            D d = (D) baseMapper.item(no);
            V v = getVO(d);
            return v;
        } catch (Exception e) {
            return null;
        }
    }

    public V item(Integer id) {
        try {
            D d = (D) baseMapper.item(id);
            V v = getVO(d);
            return v;
        } catch (Exception e) {
            return null;
        }
    }

}
